package com.mmall.controller;

import com.mmall.common.Const;
import com.mmall.pojo.User;
import com.mmall.utils.CookieUtil;
import com.mmall.utils.JsonUtil;
import com.mmall.utils.RedisPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *sission超时时间重置过滤器
 */
@Slf4j
public class SessionExpireFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("SessionExpireFilter init....");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        log.info("SessionFilter doFilter's loginToken:{}", loginToken);
        if (StringUtils.isNotEmpty(loginToken)) {
            //判断loginToken是否为空，或者为“”
            //如果不为空，符合条件，重置redis超时时间
            String userJsonStr = RedisPoolUtil.get(loginToken);
            User user = JsonUtil.stringToObj(userJsonStr, User.class);
            if (user != null) {
                RedisPoolUtil.expire(loginToken, Const.RedisExtime.SESSION_EXTIME);
                log.info("SessionFilter doFilter set session expire time success!");
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
